package com.nenglai.common.crud;

import com.nenglai.common.response.ValidateException;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 手动触发校验
 *
 * @author kongdehui
 * @date 2021/04/22 22:31
 **/
public class ValidatorUtil {

    private static final Validator validatorFast = Validation.byProvider(HibernateValidator.class).configure()
            .failFast(true).buildValidatorFactory().getValidator();
    private static final Validator validatorAll = Validation.byProvider(HibernateValidator.class).configure()
            .failFast(false).buildValidatorFactory().getValidator();

    /**
     * 校验遇到第一个不合法的字段直接返回不合法字段，后续字段不再校验
     *
     * @param domain
     * @author kongdehui
     * @date 2021/04/22 22:34
     */
    public static <T> void validateFast(T domain) throws ValidateException {
        Set<ConstraintViolation<T>> validateResult = validatorFast.validate(domain);
        if (validateResult.size() > 0) {
            Map<String, String> error = new HashMap<>();
            error.put(validateResult.iterator().next().getPropertyPath().toString(), validateResult.iterator().next().getMessage());
            throw new ValidateException(error);
        }
    }

    /**
     * 校验所有字段并返回不合法字段
     *
     * @param domain
     * @return java.util.Set<javax.validation.ConstraintViolation < T>>
     * @author kongdehui
     * @date 2021/04/22 22:34
     */
    public static <T> Set<ConstraintViolation<T>> validateAll(T domain) throws Exception {
        Set<ConstraintViolation<T>> validateResult = validatorAll.validate(domain);
        if (validateResult.size() > 0) {
            Iterator<ConstraintViolation<T>> it = validateResult.iterator();
            Map<String, String> error = new HashMap<>();
            while (it.hasNext()) {
                ConstraintViolation<T> cv = it.next();
                error.put(cv.getPropertyPath().toString(), cv.getMessage());
            }
            throw new ValidateException(error);
        }
        return validateResult;
    }
}
